package com.upyun.playdemo.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.upyun.playdemo.MainActivity;
import com.upyun.playdemo.R;
import com.upyun.playdemo.utils.Constant;
import com.upyun.playdemo.utils.OPENLOG;
import com.upyun.playdemo.utils.SharedPreferencesUtils;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * 设置界面.
 */
public class SettingFragment extends BaseView {

    @InjectView(R.id.service_addr_et)
    EditText serviceAddrEt;
    @InjectView(R.id.progressBar)
    ProgressBar progressBar;

    public SettingFragment(Activity activity) {
        super(activity);
    }

    public static SettingFragment newInstance(Activity activity) {
        SettingFragment newFragment = new SettingFragment(activity);
        return newFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_setting, null, false);
        ButterKnife.inject(this, rootView);
        // 每次进入 清理缓存. (建议还是手动清理，避免重复下载，浪费时间)
//        onClick(rootView.findViewById(R.id.clear_cache_btn));
        return rootView;
    }

    private String mServerAddr;

    @OnClick({R.id.test_btn, R.id.setting_btn, R.id.clear_cache_btn, R.id.reset_btn })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.test_btn: // 测试服务器地址.
                mServerAddr = serviceAddrEt.getText().toString();
                if (!mServerAddr.startsWith("http://")) {
                    mServerAddr = "http://" + mServerAddr;
                }
                // 如果结尾没有 '/'，就添加.
                if (mServerAddr.endsWith("/")) {
                    mServerAddr = mServerAddr.substring(0, mServerAddr.length() - 1);
                }
                String testAddr = mServerAddr + "/planevod/audios.json";
                OPENLOG.D("测试服务器地址 " + "testAddr:" + testAddr);
                progressBar.setVisibility(View.VISIBLE);
                AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                asyncHttpClient.get(testAddr, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        Toast.makeText(getActivity(), "地址测试有效", Toast.LENGTH_LONG).show();
                        progressBar.setVisibility(View.GONE);
                        // 保存有效的服务器地址，用于下次. (有问题，无法保存)
                        SharedPreferencesUtils.putString(getActivity(), Constant.SERVER_ADDR_KEY, mServerAddr + "12312321test");
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Toast.makeText(getActivity(), "输入的地址无效，请详细检查!!", Toast.LENGTH_LONG).show();
                        progressBar.setVisibility(View.GONE);
                    }
                });
                break;
            case R.id.setting_btn: // 系统设置.
                OPENLOG.D("系统设置");
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
                break;
            case R.id.clear_cache_btn: //清理缓存.
                OPENLOG.D("清理缓存");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            File file = new File(Environment.getExternalStorageDirectory(), getActivity().getPackageName());
                            for (File childFile : file.listFiles()) {
                                if (childFile.isFile()) {
                                    childFile.delete();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.reset_btn: // 刷新
                OPENLOG.D("刷新系统");
                ((MainActivity)getActivity()).stopAllVideoAndAudio(-1);
                getActivity().sendBroadcast(new Intent(Constant.UPDATE_NETWORK_ACTION));
                break;
        }
    }

}
